import axios, { AxiosError, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { ResultEnum } from "@/enums/httpEnum";
import { message } from "ant-design-vue";
import { useUserStore } from "@/stores/index";
// 创建 axios 实例
const service = axios.create({
  baseURL: "/api/v1",
  timeout: 30000,
  headers: { "Content-Type": "application/json;charset=utf-8" }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = sessionStorage.getItem("token");
    if (token) {
      config.headers["x-token"] = token;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.headers.getAuthorization) {
      const userStore = useUserStore();
      const token = response.headers["x-token"];
      userStore.token = token;
      if (token) sessionStorage.setItem("token", token);
    }
    if (response.data) {
      const { code, msg } = response.data;
      // code不是200的 统一的报错提示
      if (code !== ResultEnum.SUCCESS) {
        message.error(msg || "系统出错");
      }
    }
    return response;
  },
  (error: any) => {
    // 异常处理 TODO
    if (error.response.data) {
      const { code, msg } = error.response.data;
      if (code !== ResultEnum.SUCCESS) {
        message.error(msg || "系统出错");
      }
    } else {
      message.error(error.message);
    }
    return Promise.reject(error.message);
  }
);

export async function request<T = any, K = any>(params: ApiParams<K>): Promise<ResultData<T>> {
  try {
    const res = await service.post(params.url, params.data);
    return res.data;
  } catch (e: any) {
    // TODO
    return Promise.reject({
      code: 500,
      msg: e,
      data: null
    });
  }
}

// 导出 axios 实例
export default service;
